<?php

use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\helper\Str;
use think\helper\Arr;

/**
 * 系统设置获取函数
 * @param string $var
 * @return array|mixed|string
 * @throws \Exception
 */
if (!function_exists('setting')) {
    function setting(string $var = '', $default = '')
    {
        $list = [];
        $config = Db::name('config')->field('name,value')->select()->toArray();
        foreach ($config as $k => $val){
            $list[$val['name']] = $val['value'];
        }
        if (empty($var)) {
            return $list;
        }
        return !empty($list[$var]) ? $list[$var]: $default;
    }
}

/**
 * 获取所有子权限id 集合
 */
if (!function_exists('getAuthChildIds')) {
    function getAuthChildIds($model,$id){
        $ids = $model->where('pid',$id)->column('id');
        $list = $ids;
        if($ids){
            foreach ($ids as $k=>$v){
                $ids =  getAuthChildIds($model, $v);
                $list = array_merge($ids,$list);
            }
        }
        return $list;

    }
}
/**
 * 无限分类-权限
 * @return array
 */
if (!function_exists('cateTree')) {
    function cateTree($cate, $lefthtml = '|— ', $pid = 0, $level = 0)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['pid'] == $pid) {
                $v['level'] = $level + 1;
                $v['lefthtml'] = str_repeat($lefthtml, $level);
                $v['ltitle'] = $v['lefthtml'] . $v['title'];
                $arr[] = $v;
                $arr = array_merge($arr, cateTree($cate, $lefthtml, $v['id'], $level + 1));
            }
        }
        return $arr;
    }
}
// 将二维数组变成多维
if (!function_exists('tree')) {
    function tree($cate , $pid=0){
        $arr=array();
        foreach ($cate as $k => $v){
            if($v['pid']==$pid){
                $v['id']=$v['id'];
                $v['spread']=true;
                $arr[$k]=$v;
                $arr[$k]['children']= array_merge(tree($cate,$v['id']));
            }
        }
        return $arr;
    }
}
